package org.wenhua.yuan.and.fragment

import android.content.Context.WIFI_SERVICE
import android.net.wifi.WifiManager
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.widget.CompoundButton
import android.widget.Toast
import com.facebook.react.bridge.UiThreadUtil.runOnUiThread
import kotlinx.android.synthetic.main.fragment_im_tab.*
import org.wenhua.yuan.R
import org.wenhua.yuan.socket_client.ClientCallback
import org.wenhua.yuan.socket_client.SocketClient2
import org.wenhua.yuan.socket_server.ServerCallback
import org.wenhua.yuan.socket_server.SocketServer2

class IMTabFragment : IBaseFragment() ,ServerCallback, ClientCallback{

    private var isConnected = false
    private var isSocketOpen = false
    private var receivedMessage = ""
    private var ipadd = ""
    override fun getLayoutRes(): Int {
        return R.layout.fragment_im_tab
    }


    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        switchButton.setOnCheckedChangeListener(object : CompoundButton.OnCheckedChangeListener {
            override fun onCheckedChanged(buttonView: CompoundButton?, isChecked: Boolean) {
                receivedMessage = if (isChecked) {
                    // 客户端
                    "[接收来自服务端信息]"
                } else {
                    // 服务端
                    "[接收来自客户端信息]"
                }
            }
        })


            ipText.addTextChangedListener(object :TextWatcher{
                override fun beforeTextChanged(
                    s: CharSequence?,
                    start: Int,
                    count: Int,
                    after: Int
                ) {

                }

                override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                    ipadd = s.toString()
                }

                override fun afterTextChanged(s: Editable?) {
                }
            })
        btnConnectServer.setOnClickListener {
            connectServer(ipadd)//172.20.10.3
            Toast.makeText(context, "客户端连接中...", Toast.LENGTH_SHORT).show()
        }
        btnCloseConnect.setOnClickListener {
            closeServer()
        }
        btnStopServer.setOnClickListener {
            stopServer()
        }
        btnStartServer.setOnClickListener {
            startServer()
            Toast.makeText(context, "服务正在启动中...", Toast.LENGTH_SHORT).show()
        }


        initViews()
        textIP.text = "当前设备IP地址：${getIp()}" // 配置显示当前设备的IP地址
    }

    private fun initViews() {
        var clientMessage = ""
        btnStart.setOnClickListener {
            toast("发送")
            SocketServer2.sendToClient(ipadd)
        }
        btnSendMsg.setOnClickListener {
            toast("发送")
            SocketClient2.sendToServer(clientMessage)

        }
        msgText.addTextChangedListener(object :TextWatcher{
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                clientMessage = s.toString()
            }

            override fun afterTextChanged(s: Editable?) {
            }
        })
    }

    private fun startServer() {
        isSocketOpen = true
        SocketServer2.startServer(this)
        toast("服务已开启")
    }
    private fun stopServer() {
        isSocketOpen = false
        SocketServer2.stopServer()
        toast("服务已关闭")
    }
    private fun connectServer(ipAddress: String) {
        isConnected = true
        try {
            SocketClient2.connectSocketServer(ipAddress, this)
        } catch (e:Exception){Log.e("connectServer err>>>", e.toString())}
        toast("客户端连接已开启")
    }
    private fun closeServer() {
        isConnected = false
        SocketClient2.closeConnect()
        toast("客户端连接已关闭")
    }
    private fun getIp() =
        intToIp((context?.getSystemService(WIFI_SERVICE) as WifiManager).connectionInfo.ipAddress)

    private fun intToIp(ip: Int) =
        "${(ip and 0xFF)}.${(ip shr 8 and 0xFF)}.${(ip shr 16 and 0xFF)}.${(ip shr 24 and 0xFF)}"




    override fun onReceiveClientMessage(ipAddress: String, message: String?) {
        Log.d("服务器收到：", "消息内容：$message + 服务器IP地址：$ipAddress")
        runOnUiThread {
            textReceive.text = "${receivedMessage}[ip]$ipAddress 发送：${message}"
        }
    }

    override fun onServerWarmingTip(message: String?) {
        Log.d("服务器收到温馨提示：", message+"")
    }

    var clientMessageIndex:Int = 0
    var serverMessageIndex:Int = 0
    override fun onHeartbeatClientMessage(message: String?) {
        Log.d("Heartbeat：", message+"")
        runOnUiThread {
            textHeartbeat.text = ""+(++clientMessageIndex)+"\n"+message
        }
    }

    override fun onReceiveServerMessage(ipAddress: String, message: String?) {
        Log.e("客户端收到：", "消息内容：$message + 客户端IP地址：$ipAddress")
        runOnUiThread {
            textReceive.text = "${receivedMessage}[ip]$ipAddress${message}"
        }
    }

    override fun onWarmClientTip(message: String?) {
        Log.e("客户端收到温馨提示：", message+"")
    }

    override fun onHeartbeatServerMessage(message: String?) {
        Log.d("Heartbeat：", message+"")
        runOnUiThread {
            textHeartbeat.text = ""+(++serverMessageIndex)+"\n"+message
        }
    }


    private fun toast (text:String) {
        Toast.makeText(context, text, Toast.LENGTH_SHORT).show()
    }

}
